<template>
  <div class="exam-records">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" inline>
        <el-form-item label="考试名称">
          <el-input 
            v-model="queryParams.examTitle" 
            placeholder="请输入考试名称" 
            clearable 
            @keyup.enter="fetchExamRecords"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="进行中" value="IN_PROGRESS" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="超时" value="TIMEOUT" />
            <el-option label="已放弃" value="ABANDONED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchExamRecords" icon="Search">搜索</el-button>
          <el-button @click="resetQuery" icon="Refresh">重置</el-button>
          <el-button type="success" @click="fetchExamRecords" icon="RefreshRight">刷新</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>考试记录</span>
        </div>
      </template>
      
      <el-table 
        :data="examRecords" 
        style="width: 100%" 
        v-loading="loading"
        empty-text="暂无数据"
      >
        <el-table-column prop="examTitle" label="考试名称" min-width="120" />
        <el-table-column prop="startTime" label="开始时间" width="180" align="center" />
        <el-table-column prop="endTime" label="结束时间" width="180" align="center" />
        <el-table-column prop="duration" label="考试时长(分钟)" width="120" align="center" />
        <el-table-column prop="score" label="得分" width="80" align="center" />
        <el-table-column prop="totalScore" label="总分" width="80" align="center" />
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusDisplayName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="提交时间" width="180" align="center" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary"
              size="small" 
              icon="View"
              @click="handleView(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 考试记录详情弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        title="考试记录详情"
        width="60%"
        :before-close="handleClose"
      >
        <div class="detail-content" v-loading="detailLoading">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="考试名称">{{ examRecordDetail.examTitle }}</el-descriptions-item>
            <el-descriptions-item label="得分">{{ examRecordDetail.score }}</el-descriptions-item>
            <el-descriptions-item label="总分">{{ examRecordDetail.totalScore }}</el-descriptions-item>
            <el-descriptions-item label="得分率">{{ percentage }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusTagType(examRecordDetail.status)">
                {{ getStatusDisplayName(examRecordDetail.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ examRecordDetail.startTime }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ examRecordDetail.endTime || 'N/A' }}</el-descriptions-item>
            <el-descriptions-item label="提交时间">{{ examRecordDetail.createdAt }}</el-descriptions-item>
          </el-descriptions>
          
          <div class="answers-section" v-if="examRecordDetail.answers && examRecordDetail.answers.length > 0">
            <h3>答题详情</h3>
            <el-table :data="examRecordDetail.answers" style="width: 100%" border>
              <el-table-column prop="questionId" label="题号" width="80" align="center" />
              <el-table-column prop="answer" label="答案" min-width="200" />
              <el-table-column prop="isCorrect" label="是否正确" width="100" align="center">
                <template #default="scope">
                  <el-tag :type="scope.row.isCorrect ? 'success' : 'danger'">
                    {{ scope.row.isCorrect ? '正确' : '错误' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="score" label="得分" width="80" align="center" />
            </el-table>
          </div>
        </div>
      </el-dialog>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { examRecordApi } from '@/api/examRecords'
import type { PageResponse, ExamRecord } from '@/types'

// 响应式数据
const loading = ref(false)
const examRecords = ref<ExamRecord[]>([])
const dialogVisible = ref(false)
const detailLoading = ref(false)
const examRecordDetail = ref<ExamRecord>({} as ExamRecord)

// 查询参数
const queryParams = reactive({
  examTitle: '',
  status: ''
})

// 分页参数
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 得分率计算
const percentage = computed(() => {
  if (examRecordDetail.value.score && examRecordDetail.value.totalScore) {
    return (examRecordDetail.value.score / examRecordDetail.value.totalScore * 100).toFixed(1) + '%'
  }
  return 'N/A'
})

// 获取考试记录列表
const fetchExamRecords = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page - 1, // 后端页码从0开始
      size: pagination.size,
      examTitle: queryParams.examTitle || undefined,
      status: queryParams.status || undefined
    }
    
    const res: PageResponse<ExamRecord> = await examRecordApi.getExamRecords(params)
    examRecords.value = res.content
    pagination.total = res.totalElements
  } catch (error) {
    console.error('获取考试记录列表失败:', error)
    ElMessage.error('获取考试记录列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryParams.examTitle = ''
  queryParams.status = ''
  pagination.page = 1
  fetchExamRecords()
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pagination.size = val
  pagination.page = 1
  fetchExamRecords()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  pagination.page = val
  fetchExamRecords()
}

// 获取状态显示名称
const getStatusDisplayName = (status: string) => {
  const statusMap: Record<string, string> = {
    'IN_PROGRESS': '进行中',
    'COMPLETED': '已完成',
    'TIMEOUT': '超时',
    'ABANDONED': '已放弃'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, 'primary' | 'success' | 'warning' | 'danger' | 'info'> = {
    'IN_PROGRESS': 'primary',
    'COMPLETED': 'success',
    'TIMEOUT': 'warning',
    'ABANDONED': 'danger'
  }
  return typeMap[status] || 'info'
}

// 查看详情
const handleView = async (row: ExamRecord) => {
  dialogVisible.value = true
  detailLoading.value = true
  try {
    const res = await examRecordApi.getExamRecord(row.id)
    examRecordDetail.value = res.data
  } catch (error) {
    console.error('获取考试记录详情失败:', error)
    ElMessage.error('获取考试记录详情失败，请稍后重试')
  } finally {
    detailLoading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  examRecordDetail.value = {} as ExamRecord
}

// 组件挂载时获取数据
onMounted(() => {
  fetchExamRecords()
})
</script>

<style scoped>
.exam-records {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-content {
  padding: 20px 0;
}

.answers-section {
  margin-top: 20px;
}

.answers-section h3 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}
</style>